using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Xml;
using System.Data.SqlClient;

namespace TestData
{
    public partial class MainForm : Form
    {
        private DateTime _startTime;

        public MainForm()
        {
            InitializeComponent();

#if DEBUG
            cboCount.Items.Add("1,000");
            cboCount.Items.Add("5,000");
#endif
            cboCount.Items.Add("10,000");
            cboCount.Items.Add("20,000");
            cboCount.Items.Add("25,000");
            cboCount.Items.Add("50,000");
            cboCount.Items.Add("100,000");
            cboCount.Items.Add("250,000");
            cboCount.Items.Add("500,000");
            cboCount.Items.Add("750,000");
            cboCount.Items.Add("1,000,000");
            cboCount.Items.Add("2,000,000");
            cboCount.Items.Add("4,000,000");
            cboCount.SelectedIndex = 1;

            lblDescription.Text = "This application will create a sample database for automobiles. Choose the number of autos you wish to create and a database will be created with that number of items and related tables such as Metros, States, etc. The connection information must not point to an existing database and the user must have administrator rights.";

        }

        private void cmdBuild_Click(object sender, EventArgs e)
        {
            try
            {
                if (!Populate.CeleriqRunning())
                {
                    MessageBox.Show("The Celeriq server is not running.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                //Error Check
                txtServer.Text = txtServer.Text.Trim();
                txtUser.Text = txtUser.Text.Trim();
                txtWebsite.Text = txtWebsite.Text.Trim();
                txtDatabase.Text = txtDatabase.Text.Trim();
                if (txtServer.Text == "")
                {
                    MessageBox.Show("The server must be filled in.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else if (txtDatabase.Text == "")
                {
                    MessageBox.Show("The database must be filled in.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else if (txtUser.Text == "")
                {
                    MessageBox.Show("The user must be filled in.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                //else if(txtWebsite.Text == "")
                //{
                //  MessageBox.Show("The website folder must be filled in.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //  return;
                //}


                if (MessageBox.Show("Are you sure you wish to create the database? For a large dataset this operation might take between 20-60 minutes.", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    var masterConnection = "";
                    var connection = "";

                    if (chkTrusted.Checked)
                    {
                        masterConnection = "Data Source = " + txtServer.Text + "; Initial Catalog = master; Integrated Security = SSPI;";
                        connection = "Data Source=" + txtServer.Text + ";Initial Catalog=" + txtDatabase.Text + ";Integrated Security = SSPI;";
                    }
                    else
                    {
                        masterConnection = "Data Source=" + txtServer.Text + ";Initial Catalog=master;user id=" + txtUser.Text + ";password=" + txtPassword.Text + ";";
                        connection = "Data Source=" + txtServer.Text + ";Initial Catalog=" + txtDatabase.Text + ";user id=" + txtUser.Text + ";password=" + txtPassword.Text + ";";
                    }

                    if (!ConnectionValid(masterConnection))
                    {
                        MessageBox.Show("The master connection string is not valid.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    if (ConnectionValid(connection))
                    {
                        MessageBox.Show("The specified database cannot exist. Please specifiy a new name.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    txtDatabase.Enabled = false;
                    txtPassword.Enabled = false;
                    txtServer.Enabled = false;
                    txtUser.Enabled = false;
                    cboCount.Enabled = false;
                    cmdBuild.Enabled = false;
                    cmdCancel.Enabled = false;

                    _startTime = DateTime.Now;
                    var p = new Populate(masterConnection, connection, txtDatabase.Text, int.Parse(((string)cboCount.SelectedItem).Replace(",", "")));
                    p.Complete += p_Complete;
                    var t = new System.Threading.Thread(p.Load);
                    t.Start();

                    while (t.ThreadState == System.Threading.ThreadState.Running)
                    {
                        this.Refresh();
                        System.Threading.Thread.Sleep(1000);
                    }

                    //var endTime = DateTime.Now;
                    //MessageBox.Show("The database has been created.\nTotal time: " + endTime.Subtract(startTime).TotalSeconds.ToString("###,###,##0") + " seconds", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //cmdCancel.Enabled = true;
                    //cmdCancel.Text = "Close";

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error has occured!\n" + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private delegate void UICallback(object sender, EventArgs e);

        private void p_Complete(object sender, EventArgs e)
        {
            if (cmdBuild.InvokeRequired)
            {
                var d = new UICallback(p_Complete);
                this.Invoke(d, new object[] { sender, e });
            }
            else
            {
                var endTime = DateTime.Now;
                MessageBox.Show("The database has been created.\nTotal time: " + endTime.Subtract(_startTime).TotalSeconds.ToString("###,###,##0") + " seconds", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cmdCancel.Enabled = true;
                cmdCancel.Text = "Close";
            }
        }


        private void cmdCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cmdWebsite_Click(object sender, EventArgs e)
        {
            var D = new FolderBrowserDialog();
            D.Description = "This folder will have a configuration file written to it for the website.";
            D.SelectedPath = txtWebsite.Text;
            if (D.ShowDialog() == DialogResult.OK)
            {
                txtWebsite.Text = D.SelectedPath;
            }

        }

        private bool ConnectionValid(string connectionString)
        {
            SqlConnection connection = null;
            try
            {
                connection = new SqlConnection(connectionString);
                var command = new SqlCommand();
                command.CommandTimeout = 10;
                command.Connection = connection;
                connection.Open();
                command.CommandText = "select 1";
                command.CommandType = CommandType.Text;
                command.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
                if (connection != null)
                    connection.Close();
            }

        }

        private void chkTrusted_CheckedChanged(object sender, EventArgs e)
        {
            txtUser.Enabled = !chkTrusted.Checked;
            txtPassword.Enabled = !chkTrusted.Checked;
        }

    }
}